<template>
    <section>
        <!--高级查询form表单-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <!--
            :inline="true":行内form表单
            :model="searchForm"  双向绑定的公共前缀

            -->
            <el-form :inline="true" :model="searchForm">
                <el-form-item>
                    <el-input v-model="searchForm.name" placeholder="部门"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="searchForm.state" clearable  placeholder="请选择状态">
                        <el-option label="启用" value="0"></el-option>
                        <el-option label="禁用" value="-1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="searchDepartments">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <!--部门列表-->
        <el-table :data="departments" v-loading="listLoading"   @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60" label="序号">
            </el-table-column>
            <el-table-column prop="name" label="部门">
            </el-table-column>
            <el-table-column prop="sn" label="编号">
            </el-table-column>
            <el-table-column prop="state" label="状态" :formatter="formatState" >
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理">
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门">
            </el-table-column>
            <el-table-column label="操作" >
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--
            新增/编辑 界面
             :rules: 定义校验规则的
             ref="ruleForm"简单理解就是form表单的id一样
        -->
        <el-dialog :title="title"  :visible.sync="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" :rules="rules" ref="ruleForm"  label-width="80px" >
                <!--prop="name"：校验的字段-->
                <el-form-item label="部门" prop="name">
                    <el-input v-model="addForm.name"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="编号" prop="sn">
                    <el-input v-model="addForm.sn" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="addForm.state">
                        <el-radio class="radio" :label="0">启用</el-radio>
                        <el-radio class="radio" :label="-1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门经理" prop="managerId">
                    <el-select v-model="addForm.managerId"  clearable placeholder="请选择">
                        <el-option
                                v-for="item in managers"
                                :key="item.id"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级部门">
                    <el-cascader
                            v-model="addForm.path"
                            :options="parentDepartments"
                            :props="{ checkStrictly: true }"
                            clearable></el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addSubmit" >提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>
<script>

    export default {
        data() {
            return {
                rules: {
                    name: [
                        {required: true, message: '部门名必填', trigger: 'blur'}
                    ],
                    sn: [
                        {required: true, message: '编号必填', trigger: 'blur'}
                    ],
                    managerId: [
                        {required: true, message: '部门经理必选', trigger: 'change'}
                    ]
                },
                //上级所有的部门
                parentDepartments: [],
                //弹出框标题
                title: "",
                //是否弹出窗体，默认不弹出
                addFormVisible: false,
                //弹出框中form表单对应的data数据
                addForm: {
                    id:"",
                    //部门名
                    name: "",
                    //部门编号
                    sn: "",
                    //状态
                    state: "",
                    //部门经理
                    managerId: "",
                    //上级部门path路径
                    path: ""
                },
                //查询所有的部门经理
                managers: [],
                //高级查询form表单
                searchForm: {
                    //部门名
                    name: "",
                    state: ""
                },
                //显示列表加载框
                listLoading: false,
                //列表选中列
                sels: [],
                //部门列表
                departments: [],
                //当前页
                currentPage: 1,
                //每页条数
                pageSize: 10,
                //总条数
                total: 0
            };
        },
        methods: {
            //格式化状态
            formatState(row, column){
                return row.state == 0 ? "启用" : "禁用";
            },
            //点击复选框触发此事件        vals:返回勾选行对应的数据
            selsChange(vals){
                this.sels = vals;
            },
            //给编辑按钮注册事件
            handleEdit(index,row){
                //修改标题
                this.title = "修改";
                //能解决大部分的属性
                for(var k in this.addForm){
                    this.addForm[k] = row[k];
                }
                //对于特定属性，特定处理就可以了
                //给managerid赋值
                this.addForm.managerId = row.manager.id;
                //path应该改为数组
                this.addForm.path = this.addForm.path.split(",");
                //弹出窗体
                this.addFormVisible = true;
            },
            //给删除按钮注册事件
            handleDel(index,row){
                //提示确认删除
                this.$confirm('您确认离我而去吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.$http.delete("/department/"+row.id).then(res=>{
                        let {success, msg} = res.data;
                        if(success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            //刷新界面
                            this.loadDepartments();
                        }else{
                            this.$message.error('错了哦，这是一条错误消息');
                        }
                    })

                }).catch(() => {

                });
            },
            //批量删除
            batchRemove(){
                //提示确认删除
                this.$confirm('您确认离我而去吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.$http.patch("/department/batchRemove",this.sels).then(res=>{
                        let {success, msg} = res.data;
                        if(success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            //刷新界面
                            this.loadDepartments();
                        }else{
                            this.$message.error('错了哦，这是一条错误消息');
                        }
                    })
                }).catch(() => {

                });
            },
            //页码发生改变的时候触发此函数
            handleCurrentChange(val){
                //修改当前页
                this.currentPage = val;
                //再来分页查询
                this.loadDepartments();
            },
            //高级查询按钮对应的事件
            searchDepartments(){
                //查询第一页
                this.currentPage = 1;
                //继续查询列表
                this.loadDepartments();
            },
            //查询部门列表
            loadDepartments(){
                //显示加载框
                this.listLoading = true;
                //前端传递的分页参数(当前页，每页条数)
                let param = {
                    "currentPage": this.currentPage, "pageSize": this.pageSize,
                    "state":this.searchForm.state,"name":this.searchForm.name
                };
                //请求url地址，并且传递参数
                this.$http.patch("/department",param).then(res=>{
                    //关闭加载框
                    this.listLoading = false;
                    let {total,list} = res.data;
                    //返回分页列表
                    this.departments = list;
                    //返回总条数
                    this.total = total;
                })
            },
            //点击新增按钮注册事件
            handleAdd(){
                //设置标题
                this.title = "新增";
                //先重置
                if(this.$refs["ruleForm"]){
                    //当出现了校验规则的时候，才能进行重置
                    this.$refs["ruleForm"].resetFields();//this.$refs.ruleForm.resetFields()
                }
                //手动清空form表单
                for(var k in this.addForm){
                    this.addForm[k] = "";
                }
                this.addForm.state = 0;
                //弹出窗体
                this.addFormVisible = true;
            },
            //给提交按钮注册事件
            addSubmit(){
                //手动创建一个manager对象
                let manager = {"id": this.addForm.managerId};
                //手动给addForm添加manager属性
                this.addForm.manager = manager;
                //获取path   格式为: [1,5,6]
                let path = this.addForm.path;
                //手动创建parent对象
                let parent = {"id": path[path.length - 1]};
                //手动给addForm添加parent属性
                this.addForm.parent = parent;
                //把path数组改为字符串      1,5,6
                this.addForm.path = path.toString();
                //提交form表单之前必须要进行校验
                this.$refs["ruleForm"].validate((valid) => {
                    //校验通过之后，执行if语句中的内容
                    if (valid) {
                        this.$http.post("/department", this.addForm).then(res => {
                            let {success, msg} = res.data;
                            if(success){
                                //关闭模态框
                                this.addFormVisible = false;
                                //刷新界面
                                this.loadDepartments();
                                //刷新上级部门
                                this.loadParentDepartments();
                            }else{
                                this.$message.error(msg);
                            }
                        });
                    }
                });

            },
            //查询所有的部门经理
            loadManagers(){
                this.$http.patch("/department/findManagers").then(res=>{
                    if(!res.success&& res.data==='noLogin'){
                        //销毁token
                        //销毁登录信息
                        // 跳转到登录界面
                    }
                    this.managers = res.data;
                })
            },
            //查询所有部门树列表
            loadParentDepartments(){
                this.$http.patch("/department/findDepartmentTree").then(res => {
                    if(!res.success&& res.data==='noLogin'){
                        //销毁token
                        //销毁登录信息
                        // 跳转到登录界面
                    }
                    this.parentDepartments = res.data;
                });
            }
        },
        mounted() {
            //加载所有的部门分页列表
            this.loadDepartments();
            //加载所有的部门经理
            this.loadManagers();
            //查询所有的上级部门
            this.loadParentDepartments();
        }
    }

</script>